package com.zxl.yjb.activity.im;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zxl.yjb.R;
import com.zxl.yjb.activity.payfee.PayFeeActivity;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.OrderBindBean;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.LogUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

public class ConversationActivity extends BaseActivity  {
    private static final String TAG = "ConversationActivity";
    @BindView(R.id.tv_page_title)
    TextView tvPageTitle;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.ll_send_order)
    LinearLayout llSendOrder;
    private String title;
    private String order;
    private LoginSucessBean loginSucessBean;
    private String targetId;
    private String origin = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Intent intent = getIntent();
        title = intent.getData().getQueryParameter("title");
        order = intent.getData().getQueryParameter("order_sn");
        targetId = intent.getData().getQueryParameter("targetId");
        origin = intent.getData().getQueryParameter("origin");
        Object bean = SaveBeanUtil.getBean(this, Const.VIPINFO);
        if (bean != null) {
            loginSucessBean = (LoginSucessBean) bean;
        }
        RongIM.getInstance().setSendMessageListener(new MySendMessageListener());
        initView();
        getOrderListForUser();
    }

    @Override
    protected void initView() {
        tvPageTitle.setText(title);
        tvConfirm.setVisibility(View.VISIBLE);
        tvConfirm.setText("加入黑名单");
    }


    @OnClick({R.id.iv_back, R.id.tv_page_title,R.id.ll_send_order,R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_page_title:

                break;
            case R.id.ll_send_order:
                paySelecte();
                break;
            case R.id.tv_confirm://加入黑名单
                addBlackList();

                break;
        }
    }

    //加入黑名单
    private void addBlackList() {
        DataManager dataManager = new DataManager();
        Map<String,String> map = new HashMap<>();
        map.put("relationid",targetId);
        map.put("attribute","2");
        ObserverOnNextListener<Object> listener = new ObserverOnNextListener<Object>() {
            @Override
            public void onNext(Object callback) {
                ToastUtils.show(ConversationActivity.this,"已将此人加入黑名单");
//                tvConfirm.setVisibility(View.GONE);
            }
        };
        dataManager.addFriend(new ProgressObserver<Object>(listener,this),map);
    }

    /**
     * 选择支付方式
     */
    private void paySelecte() {
        Intent intent = new Intent(getApplicationContext(), PayFeeActivity.class);
        intent.putExtra("targetId", targetId);
        startActivity(intent);
    }

    private void getOrderListForUser() {
        DataManager dataManager = new DataManager();
        Map<String, String> map = new HashMap<>();
        map.put("user id",loginSucessBean.getUid()+"");
        map.put("chatuid", targetId);
        map.put("page", "1");
        map.put("count", "10");
        ObserverOnNextListener<List<OrderBindBean>> listener = new ObserverOnNextListener<List<OrderBindBean>>() {
            @Override
            public void onNext(List<OrderBindBean> orderBindBeans) {
                if (orderBindBeans.size() > 0&&orderBindBeans.get(0).getRequest_id()==loginSucessBean.getUid()) {
                    if (!"sos".equals(origin))
                        llSendOrder.setVisibility(View.VISIBLE);
                }
            }
        };
        dataManager.getOrderListForUser(new ProgressObserver<List<OrderBindBean>>(listener, this), map);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        RongIM.getInstance().setSendMessageListener(null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent)
    {
        switch (messageEvent.getMessage()) {
            case "paySuccess":
                finish();
                break;
        }
    }


    private class MySendMessageListener implements RongIM.OnSendMessageListener {

        /**
         * 消息发送前监听器处理接口（是否发送成功可以从 SentStatus 属性获取）。
         * @param message 发送的消息实例。
         * @return 处理后的消息实例。
         */
        @Override
        public Message onSend(Message message) {
            //开发者根据自己需求自行处理逻辑
            order = "987654321";
            MessageContent messageContent = message.getContent();
           if (messageContent instanceof TextMessage ){
               ((TextMessage) messageContent).setExtra(order);
           } else if (messageContent instanceof ImageMessage ) {
               ((ImageMessage)messageContent).setExtra(order);
           } else if (messageContent instanceof LocationMessage) {
               ((LocationMessage)messageContent).setExtra(order);
           }

            return message;
        }

        /**
         * 消息在 UI 展示后执行/自己的消息发出后执行,无论成功或失败。
         *
         * @param message              消息实例。
         * @param sentMessageErrorCode 发送消息失败的状态码，消息发送成功 SentMessageErrorCode 为 null。
         * @return true 表示走自己的处理方式，false 走融云默认处理方式。
         */
        @Override
        public boolean onSent(Message message,RongIM.SentMessageErrorCode sentMessageErrorCode) {
            if(message.getSentStatus()== Message.SentStatus.FAILED){
                if(sentMessageErrorCode== RongIM.SentMessageErrorCode.NOT_IN_CHATROOM){
                    //不在聊天室
                }else if(sentMessageErrorCode== RongIM.SentMessageErrorCode.NOT_IN_DISCUSSION){
                    //不在讨论组
                }else if(sentMessageErrorCode== RongIM.SentMessageErrorCode.NOT_IN_GROUP){
                    //不在群组
                }else if(sentMessageErrorCode== RongIM.SentMessageErrorCode.REJECTED_BY_BLACKLIST){
                    //你在他的黑名单中
                }
            }

            MessageContent messageContent = message.getContent();

            if (messageContent instanceof TextMessage) {//文本消息
                TextMessage textMessage = (TextMessage) messageContent;
                LogUtil.d(TAG, "onSent-TextMessage:" + textMessage.getContent());
            } else if (messageContent instanceof ImageMessage) {//图片消息
                ImageMessage imageMessage = (ImageMessage) messageContent;
                LogUtil.d(TAG, "onSent-ImageMessage:" + imageMessage.getRemoteUri());
            } else if (messageContent instanceof VoiceMessage) {//语音消息
                VoiceMessage voiceMessage = (VoiceMessage) messageContent;
                LogUtil.d(TAG, "onSent-voiceMessage:" + voiceMessage.getUri().toString());
            } else if (messageContent instanceof RichContentMessage) {//图文消息
                RichContentMessage richContentMessage = (RichContentMessage) messageContent;
                LogUtil.d(TAG, "onSent-RichContentMessage:" + richContentMessage.getContent());
            } else {
                LogUtil.d(TAG, "onSent-其他消息，自己来判断处理");
            }
            return false;
        }
    }
}
